package com.example.administrator.demo.recycle;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;

public abstract class RecyclerViewAdapter<T> extends RecyclerView.Adapter<RecyclerViewAdapter.CommonViewHolder> {

    private Context mContext;
    private LayoutInflater mInflater;
    private int mLayoutResId;
    private List<T> mArrayList;



    public RecyclerViewAdapter(Context context, int layoutResId, List<T> data) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(context);
        this.mLayoutResId = layoutResId;
        this.mArrayList = data;
    }

    @Override
    public CommonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new CommonViewHolder(mInflater.inflate(mLayoutResId, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerViewAdapter.CommonViewHolder holder, int position, List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        if(position == mArrayList.size()) return;
        if (null == payloads || payloads.size() < 1) {
            onBindViewHolder(holder, position);
        } else{
            for (Object payload : payloads) {
            }
        }
    }

    @Override
    public void onBindViewHolder(RecyclerViewAdapter.CommonViewHolder holder, int position) {
        T t = mArrayList.get(position);
        convert(holder, position, t);
    }

    public abstract void convert(CommonViewHolder holder, int position, T t);

    @Override
    public int getItemCount() {
        return mArrayList.size();
    }

    /***RecyclerView的通用ViewHolder***/
    public class CommonViewHolder extends RecyclerView.ViewHolder {

        private SparseArray<View> mItemViews;
        private View convertView;

        public CommonViewHolder(View view) {
            super(view);
            this.convertView = view;
            mItemViews = new SparseArray<>();
        }

        public <T extends View> T getView(int viewId){
            View view = mItemViews.get(viewId);
            if(view == null){
                view = convertView.findViewById(viewId);
                mItemViews.put(viewId, view);
            }
            return (T) view;
        }
    }
}
